﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using eduscrum.Models;
using eduscrum.DAL;
using eduscrum.Helper;
using eduscrum.ViewModels;
using System;

namespace eduscrum.Controllers
{
    
    public class ProjectController : Controller
    {
        private SystemContext db = new SystemContext();

        //
        // GET: /Project/

        public ViewResult Index()
        {
            var projects = db.Projects.ToList();
            List<ProjectVM> projectsVM = AutoMapper.Mapper.Map<List<Project>,List<ProjectVM>>(projects);
            return View(projectsVM);
        }

        //
        // GET: /Project/Create

        public ActionResult Create()
        {
            var viewModel = new ProjectVM();
            viewModel.StartDate = DateTime.Now;
            viewModel.EndDate = DateTime.Now;
            return View("Create", viewModel);
        } 

        //
        // POST: /Project/Create

        [HttpPost]
        public ActionResult Create(ProjectVM projectToCreate)
        {
            if (ModelState.IsValid)
            {
                projectToCreate.Locked = false;
                Project newProject = new Project();
                AutoMapper.Mapper.Map(projectToCreate, newProject);
                newProject.Phases = new List<Phase>();
                newProject.Sprints = new List<Sprint>();
                for (int i = 0; i < projectToCreate.PhaseCount; i++)
                {
                    if (i == projectToCreate.PhaseCount - 1)
                    {
                        newProject.Phases.Add(new Phase { Name = DefaultSettings.PhaseNames.Last(), Project = newProject });
                    }
                    else if (i >= DefaultSettings.PhaseNames.Length - 1)
                    {
                        newProject.Phases.Add(new Phase { Name = "Phase " + (i + 1), Project = newProject });
                    }
                    else if (i < DefaultSettings.PhaseNames.Length - 1)
                    {
                        newProject.Phases.Add(new Phase { Name = DefaultSettings.PhaseNames[i], Project = newProject });
                    }
                }
                int daysTotal = ((newProject.EndDate - newProject.StartDate).Days) + 1; // Add an extra day to include end date
                int sprintCount = daysTotal / newProject.SprintDuration;
                int remainingDays = daysTotal % newProject.SprintDuration;


                for (int i = 0; i < sprintCount; i++)
                {
                    newProject.Sprints.Add(new Sprint
                        {
                            StartDate = newProject.StartDate.AddDays(i * (newProject.SprintDuration)),
                            Project = newProject,
                            SprintBacklog = new List<UserStory>(),
                            EndDate = newProject.StartDate.AddDays(((i + 1) * newProject.SprintDuration) - 1)
                        });
                }

                if (remainingDays > 0)
                {
                    newProject.Sprints.Add(new Sprint
                    {
                        StartDate = newProject.Sprints.Last().EndDate.AddDays(1),
                        Project = newProject,
                        SprintBacklog = new List<UserStory>(),
                        EndDate = newProject.EndDate
                    });
                }

                db.Projects.Add(newProject);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(projectToCreate);
        }
        
        //
        // GET: /Project/Edit/5
 
        public ActionResult Edit(int id)
        {
            var projects = db.Projects.ToList();
            List<ProjectVM> projectsVM = AutoMapper.Mapper.Map<List<Project>, List<ProjectVM>>(projects);
            ProjectVM projectVM = new ProjectVM();
            AutoMapper.Mapper.Map(db.Projects.Find(id), projectVM);
            ViewData["Project"] = projectVM;
            ViewBag.Project = projectVM;
            TempData["Project"] = projectVM;
            ViewBag.Backlog = AutoMapper.Mapper.Map<List<UserStory>, List<UserStoryVM>>(db.UserStories.Where(u => u.Project.ProjectID == id).ToList());
            return View(projectsVM);
        }

        //
        // POST: /Project/Edit/5

        [HttpPost]
        public ActionResult Edit(ProjectVM projectToEditVM)
        {
            var projects = db.Projects.ToList();
            ViewData["Project"] = projectToEditVM;
            List<ProjectVM> projectsVM = AutoMapper.Mapper.Map<List<Project>, List<ProjectVM>>(projects);
            ViewBag.Backlog = AutoMapper.Mapper.Map<List<UserStory>, List<UserStoryVM>>(db.UserStories.Where(u => u.Project.ProjectID == projectToEditVM.ProjectID).ToList());
            if (ModelState.IsValid)
            {
                Project projectEdited = db.Projects.Find(projectToEditVM.ProjectID);
                
                // Cowboy Trick :-S For at undgå at lister bliver overskrevet med tomme lister når der mappes
                var backlog = projectEdited.Backlog;
                var phases = projectEdited.Phases;
                var sprints = projectEdited.Sprints;
                AutoMapper.Mapper.Map(projectToEditVM, projectEdited);
                projectEdited.Backlog = backlog;
                projectEdited.Phases = phases;
                projectEdited.Sprints = sprints;

                db.Entry(projectEdited).State = EntityState.Modified;
                db.SaveChanges();

                projects = db.Projects.ToList();
                projectsVM = AutoMapper.Mapper.Map<List<Project>, List<ProjectVM>>(projects);
                return View(projectsVM);
            }
            return View(projectsVM);
        }

        //
        // GET: /Project/Delete/5
 
        public ActionResult Delete(int id)
        {
            Project projectToDelete = db.Projects.Find(id);
            db.Projects.Remove(projectToDelete);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}